<template>
  <div>
    <span>获取验证码({{ time }}s)</span>
  </div>
</template>

<script setup lang="ts" name="CountDown">
//引入组合式API函数ref和reactive和计算属性computed
import { ref, watch } from 'vue'

// 定义一个响应式数据记录倒计时
let time = ref<number>(5)

//接收父组件传递过来的props参数flag:用于控制倒计时组件的显示和隐藏
let props = defineProps(['flag'])
//接收父组件传递过来的自定义事件
let $emit = defineEmits(['getFlag'])

//监听props参数flag的变化
watch(
  () => props.flag,
  () => {
    //开启定时器
    let timer = setInterval(() => {
      time.value--
      if (time.value == 0) {
        //通知父组件倒计时模式结束
        $emit('getFlag', false)
        //清除定时器
        clearInterval(timer)
      }
    }, 1000)
  },
  {
    immediate: true,
  }
)
</script>

<style scoped lang="scss"></style>